package com.kye.express.business.waybill.waybill_detail;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jakewharton.rxbinding2.widget.TextViewAfterTextChangeEvent;
import com.kennyc.bottomsheet.BottomSheet;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.base.utils.DateUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.business.map.MapUtils;
import com.kye.express.business.score.ScoreActivity;
import com.kye.express.databinding.ActivityWaybillDetailBinding;
import com.kye.express.databinding.BottomSheetWaybillModifyPresentTimeBinding;
import com.kye.express.utils.DrawableUtils;
import com.kye.express.utils.PhoneUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.bean.dstance.DstanceBean;
import com.kye.model.bean.logistics.LogisticsDriverInfoBean;
import com.kye.model.bean.logistics.LogisticsUrgeResultBean;
import com.kye.model.bean.logistics.LogisticsWayBillDetailResultBean;
import com.kye.model.bean.logistics.LogisticsWayBillResultDataBean;
import com.kye.model.bean.user.User;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import cn.carbswang.android.numberpickerview.library.NumberPickerView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class WayBillDetailActivity extends BaseAppCompatActivity implements WayBillDetailContract.WayBillDetailView {

    private static final int REQUEST_CODE_SCORE = 2000;
    private static String TAG_LOGISTICS_WAYBILL = "TAG_LOGISTICS_WAYBILL";
    private static String TAG_LOGISTICS_PLAN_RECEIVE_DATE = "TAG_LOGISTICS_PLAN_RECEIVE_DATE";
    private static String TAG_LOGISTICS_PLAN_RECEIVE_START_TIME = "TAG_LOGISTICS_PLAN_RECEIVE_START_TIME";
    private static String TAG_LOGISTICS_PLAN_RECEIVE_END_TIME = "TAG_LOGISTICS_PLAN_RECEIVE_END_TIME";
    private ActivityWaybillDetailBinding binding;
    private WayBillDetailContract.WayBillDetailPresenter presenter;
    private Dialog dialog; // loading dialog
    private User userInfo;
    private MaterialDialog showUrgeSuccessDialog; // 催件成功提示
    private MaterialDialog showUrgeMessageDialog; // 催件留言窗口
    private Disposable subscribeMessageInput;
    private String urgeMessage; // 催件留言
//    private LogisticsItemBean logisticsItemBean; // 运单列表数据
    private String waybill; // 当前运单号
    private LogisticsWayBillDetailResultBean logisticsWayBillDetailResultBean; // 运单详情请求结果
    private String selectedPlanReceivedDate; // 修改定时派送的日期
    private String startTime; // 修改定时派送的开始时间
    private String endTime; // 修改定时派送的结束时间
    private RxPermissions mRxPermissions;

    private BaiduMap mMap;
    private LatLng mCustomLatLng;
    private Marker mCarMarker;
    private Polyline mPolyline;

    public static Intent newStartIntent(Context context, String waybill) {
        Intent intent = new Intent(context, WayBillDetailActivity.class);
        intent.putExtra(TAG_LOGISTICS_WAYBILL, waybill);
        return intent;
    }

    public static void startActivity(Activity activity, int requestCode, String waybill) {
        Intent intent = new Intent(activity, WayBillDetailActivity.class);
        intent.putExtra(TAG_LOGISTICS_WAYBILL, waybill);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void startActivity(Context context, String waybill) {
        Intent intent = new Intent(context, WayBillDetailActivity.class);
        intent.putExtra(TAG_LOGISTICS_WAYBILL, waybill);
        context.startActivity(intent);
    }

    public static void startActivityForNewTask(Context context, String waybill) {
        Intent intent = new Intent(context, WayBillDetailActivity.class);
        intent.putExtra(TAG_LOGISTICS_WAYBILL, waybill);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            waybill = getIntent().getStringExtra(TAG_LOGISTICS_WAYBILL);
        } else {
            waybill = savedInstanceState.getString(TAG_LOGISTICS_WAYBILL);
            startTime = savedInstanceState.getString(TAG_LOGISTICS_PLAN_RECEIVE_START_TIME);
            endTime = savedInstanceState.getString(TAG_LOGISTICS_PLAN_RECEIVE_END_TIME);
            selectedPlanReceivedDate = savedInstanceState.getString(TAG_LOGISTICS_PLAN_RECEIVE_DATE);
        }
        binding = DataBindingUtil.setContentView(this, R.layout.activity_waybill_detail);
        presenter = new WayBillDetailContract.WayBillDetailPresenter();
        mRxPermissions = new RxPermissions(this);
        initToolbar(savedInstanceState);
        initViews(savedInstanceState);
        initEvents(savedInstanceState);
        initData(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString(TAG_LOGISTICS_WAYBILL, waybill);
        outState.putString(TAG_LOGISTICS_PLAN_RECEIVE_START_TIME, startTime);
        outState.putString(TAG_LOGISTICS_PLAN_RECEIVE_END_TIME, endTime);
        outState.putString(TAG_LOGISTICS_PLAN_RECEIVE_DATE, selectedPlanReceivedDate);
        super.onSaveInstanceState(outState);
    }

    private void initToolbar(Bundle savedInstanceState) {
        setSupportActionBar(binding.toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        binding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        binding.toolbar.setTitleTextColor(getResources().getColor(R.color.white));
    }

    private void initViews(Bundle savedInstanceState) {
        mMap = binding.mapView.getMap();
        mMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
    }

    private void initEvents(Bundle savedInstanceState) {
        RxView.clicks(binding.llErrorNetCustom.btErrorNetRetry)
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llErrorServerCustom.btErrorServerRetry)
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.scoreToScore)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        /**
                         * todo : 评分
                         */
                        Intent intent = ScoreActivity.newStartIntentForScoreWayBill(WayBillDetailActivity.this, logisticsWayBillDetailResultBean.getResult().get(0).getWaybill());
                        startActivityForResult(intent, REQUEST_CODE_SCORE);
                    }
                });
        RxView.clicks(binding.imageButtonCallToDriver)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {

                    private MaterialDialog mDialog;

                    @Override
                    public void accept(Object o) throws Exception {
                        /**
                         * todo : 拨打取件司机电话
                         */
                        if (mDialog == null) {
                            mDialog = new MaterialDialog.Builder(WayBillDetailActivity.this)
                                    .title("温馨提示")
                                    .content("是否拨打取件司机电话")
                                    .positiveText("确认拨打")
                                    .negativeText("取消")
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            /**
                                             * todo : 缺失字段
                                             */
                                            LogisticsDriverInfoBean driverInfo = binding.getDriverInfo();
                                            if (driverInfo != null) {
                                                PhoneUtils.call(WayBillDetailActivity.this, driverInfo.getTel());
                                            }
                                        }
                                    })
                                    .build();
                        }
                        mDialog.show();
                    }
                });
        RxView.clicks(binding.helpToCall)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {

                    private MaterialDialog mDialog;

                    @Override
                    public void accept(Object o) throws Exception {
                        /**
                         * todo : 联系跨越专员
                         */
                        if (mDialog == null) {
                            mDialog = new MaterialDialog.Builder(WayBillDetailActivity.this)
                                    .title("温馨提示")
                                    .content("是否拨打跨越专员电话")
                                    .positiveText("确认拨打")
                                    .negativeText("取消")
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            PhoneUtils.call(WayBillDetailActivity.this, logisticsWayBillDetailResultBean.getResult().get(0).getAssistantPhone());
                                        }
                                    })
                                    .build();
                        }
                        mDialog.show();
                    }
                });
        RxView.clicks(binding.helpToCall24Hour)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {

                    private MaterialDialog mDialog;

                    @Override
                    public void accept(Object o) throws Exception {
                        /**
                         * todo : 联系24小时客服
                         */
                        if (mDialog == null) {
                            mDialog = new MaterialDialog.Builder(WayBillDetailActivity.this)
                                    .title("温馨提示")
                                    .content("是否拨打24小时客服电话")
                                    .positiveText("确认拨打")
                                    .negativeText("取消")
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            PhoneUtils.call(WayBillDetailActivity.this, "4008-098-098");
                                        }
                                    })
                                    .build();
                        }
                        mDialog.show();
                    }
                });
        RxView.clicks(binding.urge)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        /**
                         * todo : 催件
                         */
                        presenter.postWaybillUrge(logisticsWayBillDetailResultBean.getResult().get(0).getWaybill(), userInfo);
                    }
                });
        RxView.clicks(binding.modifyPresentTime)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        /**
                         * todo : 修改预送时间
                         */
                        showModifyPresentTimeBottomSheet(presenter.getDaysShow(), presenter.getNormalDayTimesShow());
                    }
                });
    }

    private void initData(Bundle savedInstanceState) {
        binding.statusLayout.showLoadingView();
        presenter.bind(this);
        presenter.initLBSTraceClient(this);
        setResult(Activity.RESULT_CANCELED);
    }

    @Override
    public void onUser(User user) {
        userInfo = user;
        if (user.isLogin()) {
            binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
                @Override
                public void onLoading() {
                    presenter.getLogisticsWayBillDetail(user, waybill);
                }
            });
            presenter.getLogisticsWayBillDetail(user, waybill);
        } else {
            ToastManager.showCenterForShort("请先登录");
            finish();
        }
    }

    @Override
    public void getLogisticsWayBillDetailSuccess(LogisticsWayBillDetailResultBean logisticsWayBillDetailResultBean) {
        this.logisticsWayBillDetailResultBean = logisticsWayBillDetailResultBean;
        /**
         *  "waybillNumber": 0,
         *  "abnormalReturns": "获取运单信息失败",
         */
        LogisticsWayBillResultDataBean logisticsWayBillResultDataBean = logisticsWayBillDetailResultBean.getResult().get(0);
        String signingTime = logisticsWayBillResultDataBean.getSigningTime();
        if (TextUtils.isEmpty(signingTime)) {
            getSupportActionBar().setTitle("待签收");
        } else {
            getSupportActionBar().setTitle("已签收");
        }
        String abnormalReturns = logisticsWayBillResultDataBean.getAbnormalReturns();
        int waybillNumber = logisticsWayBillDetailResultBean.getWaybillNumber();
        if (waybillNumber <= 0 && !TextUtils.isEmpty(abnormalReturns)) {
            binding.statusLayout.showCustomView();
            binding.llWaybillError.tvErrorText.setText(logisticsWayBillResultDataBean.getAbnormalReturns());
        } else {
            binding.statusLayout.showContentView();
            // databinding更新
            binding.setDetailData(logisticsWayBillResultDataBean);
            binding.setWaybill(waybill);
            // 评分等级
            int rating = logisticsWayBillResultDataBean.getRating();
            if (rating != 0) {
                binding.scoreStartsResult.setRating(6 - rating);
                switch (rating) {
                    case 1:
                        binding.scoreMessage.setText("非常满意");
                        break;
                    case 2:
                        binding.scoreMessage.setText("比较满意");
                        break;
                    case 3:
                        binding.scoreMessage.setText("一般");
                        break;
                    case 4:
                        binding.scoreMessage.setText("不满意");
                        break;
                    case 5:
                        binding.scoreMessage.setText("非常不满意");
                        break;
                    default:
                        binding.scoreMessage.setText("比较满意");
                        break;
                }
            }
            // 运单信息
            Calendar calendar = DateUtils.dateStringToCalendar(logisticsWayBillResultDataBean.getPlanArriveTime(), "yyyy-MM-dd HH:mm");
            String planReceiveTime = DateUtils.getDateStringByDate(calendar.getTime(), "MM-dd HH:mm");
            binding.planReceiveTime.setText(planReceiveTime);
            // 路由信息更新
            presenter.updateLogisticsRounterStatus(logisticsWayBillResultDataBean);
        }
    }

    @Override
    public void updateLogisticsRounterStatus(List<RouterStatusTimeLineView.RouterStatusTimeLineModel> routerStatusTimeLineModels, boolean isFinished) {
        if (routerStatusTimeLineModels.size() <= 0) {
            binding.contentRouterView.setVisibility(View.GONE);
        } else {
            binding.contentRouterView.setRouterStatusDataList(routerStatusTimeLineModels);
            binding.contentRouterView.setFinishedForView(isFinished);
        }
    }

    @Override
    public void getLogisticsWayBillDetailFailed(String msg) {
        ToastManager.showCenterForShort(msg);
        binding.statusLayout.showErrorServerView();
    }

    @Override
    public void getLogisticsWayBillDetailFailed(Throwable e) {
        ToastManager.showCenterForShort(e.getMessage());
        binding.statusLayout.showErrorNetworkView();
    }

    @Override
    public void postWayBillUrgeSuccess(LogisticsUrgeResultBean logisticsUrgeResultBean) {
        showUrgeSuccessDialog = new MaterialDialog.Builder(WayBillDetailActivity.this)
                .customView(R.layout.order_logistics_urge, true)
                .positiveText("知道了")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        /**
                         * todo : 刷新
                         */
                        presenter.refreshLogisticsWayBillDetail(userInfo, waybill);
                    }
                })
                .positiveColor(getResources().getColor(R.color.purple_0))
                .negativeText("留言")
                .negativeColor(getResources().getColor(R.color.black_666))
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        /**
                         * todo : 催件成功，更新view
                         */
                        showUrgeSuccessDialog.dismiss();
                        showWaybillUrgeMessagePostBox();

                    }
                })
                .backgroundColor(getResources().getColor(R.color.window_background))
                .show();
        showUrgeSuccessDialog.setCancelable(false);

        // 催件成功，更新返回结果
        setResult(Activity.RESULT_OK);
    }

    @Override
    public void getDriverInfoSuccess(LogisticsDriverInfoBean logisticsDriverInfoBean) {
        binding.setDriverInfo(logisticsDriverInfoBean);
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    public void showWaybillUrgeMessagePostBox() {
        showUrgeMessageDialog = new MaterialDialog.Builder(WayBillDetailActivity.this)
                .title("留言")
                .customView(R.layout.order_logistics_urge_message, true)
                .positiveText("确认")
                .positiveColor(getResources().getColor(R.color.purple_0))
                .negativeText("取消")
                .negativeColor(getResources().getColor(R.color.black_666))
                .backgroundColor(getResources().getColor(R.color.window_background))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (TextUtils.isEmpty(urgeMessage)) {
                            ToastManager.showCenterForShort("留言不能为空");
                        } else {
                            presenter.postWaybillUrgeMessage(urgeMessage, userInfo, logisticsWayBillDetailResultBean.getResult().get(0).getWaybill());
                        }
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        showUrgeMessageDialog.dismiss();
                    }
                })
                .dismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (subscribeMessageInput != null && !subscribeMessageInput.isDisposed()) {
                            subscribeMessageInput.dispose();
                            subscribeMessageInput = null;
                        }
                        /**
                         * todo : 刷新
                         */
                        presenter.refreshLogisticsWayBillDetail(userInfo, waybill);
                    }
                })
                .show();
        showUrgeMessageDialog.setCancelable(false);
        subscribeMessageInput = RxTextView.afterTextChangeEvents(showUrgeMessageDialog.getCustomView().findViewById(R.id.message))
                .subscribe(new Consumer<TextViewAfterTextChangeEvent>() {
                    @Override
                    public void accept(TextViewAfterTextChangeEvent textViewAfterTextChangeEvent) throws Exception {
                        urgeMessage = textViewAfterTextChangeEvent.editable().toString();
                    }
                });
    }

    @Override
    public void postWayBillUrgeMessageSuccess() {
        if (showUrgeMessageDialog != null && showUrgeMessageDialog.isShowing()) {
            showUrgeMessageDialog.dismiss();
        }
    }

    @Override
    public void getLogisticsSendDistance(DstanceBean dstanceBean, String waybill) {
        binding.setShowMap(true);
        binding.setDstanceBean(dstanceBean);

        LatLng carLatLng = new LatLng(dstanceBean.getCarY(), dstanceBean.getCarX());
        mCustomLatLng = new LatLng(dstanceBean.getCustY(), dstanceBean.getCustX());

        mCarMarker = (Marker) mMap.addOverlay(new MarkerOptions()
                .position(carLatLng)
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.icon_car_location)));

        Marker csutomMarker = (Marker) mMap.addOverlay(new MarkerOptions()
                .position(mCustomLatLng)
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromBitmap(DrawableUtils.getBitmap(getResources().getDrawable(R.drawable.icon_custom_location)))));

        mPolyline = (Polyline) mMap.addOverlay(new PolylineOptions().width(5)
                .color(getResources().getColor(R.color.black_alpha_35)).points(Arrays.asList(carLatLng, mCustomLatLng)));
        mPolyline.setDottedLine(true);

        MapUtils.zoomToSpan(mMap, false, carLatLng, mCustomLatLng);
        MapUtils.moveCenterPoint(mMap, false, carLatLng, mCustomLatLng);

        presenter.getHistoryTrack(dstanceBean.getTerminalID(), waybill);
    }

    @Override
    public void updateWaybillDeliveryDistanceInfo(DstanceBean dstanceBean) {
        binding.setDstanceBean(dstanceBean);
    }

    @Override
    public void onMoveCar(LatLng latLng) {
        if (mCarMarker == null) return;

        mCarMarker.setPosition(latLng);
        mPolyline.setPoints(Arrays.asList(latLng, mCustomLatLng));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SCORE: {
                Logger.d("onActivityResult resultCode : " + resultCode);
                if (resultCode == Activity.RESULT_OK) {
                    /**
                     * todo : 完成评分，刷新数据
                     */
//                    binding.statusLayout.showLoadingView();
                    presenter.refreshLogisticsWayBillDetail(userInfo, waybill);
                }
                break;
            }
        }
    }

    private void showModifyPresentTimeBottomSheet(String[] selectDays, String[] selectTimes) {
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        BottomSheetWaybillModifyPresentTimeBinding binding = DataBindingUtil.inflate(layoutInflater, R.layout.bottom_sheet_waybill_modify_present_time, null, false);
        final BottomSheet bottomSheet = new BottomSheet.Builder(this)
                .setView(binding.getRoot()).create();
        /**
         * todo :
         */
        binding.pickerDay.setOnValueChangedListener(new NumberPickerView.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPickerView picker, int oldVal, int newVal) {
                int length = selectDays.length;
                /**
                 * 更新选择时间
                 */
                if (newVal == 0) {
                    // 第一天
                    binding.pickerTime.refreshByNewDisplayedValues(presenter.getFirstDayTimesShow());
                } else if (newVal == length - 1) {
                    // 最后一天
                    binding.pickerTime.refreshByNewDisplayedValues(presenter.getLastDayTimesShow());
                } else {
                    // 中间
                    binding.pickerTime.refreshByNewDisplayedValues(presenter.getNormalDayTimesShow());
                }
                selectedPlanReceivedDate = presenter.getDays()[newVal].getDate();
            }
        });
        binding.pickerTime.setOnValueChangedListener(new NumberPickerView.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPickerView picker, int oldVal, int newVal) {
                String contentByCurrValue = picker.getContentByCurrValue();
                startTime = contentByCurrValue.split("-")[0] + ":00";
                endTime = contentByCurrValue.split("-")[1] + ":00";
            }
        });
        binding.pickerDay.refreshByNewDisplayedValues(selectDays);
        binding.pickerTime.refreshByNewDisplayedValues(selectTimes);
        binding.pickerDay.smoothScrollToValue(2);
        bottomSheet.show();
        RxView.clicks(binding.modifyCancel)
                .compose(this.bindToLifecycle())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        bottomSheet.dismiss();
                    }
                });
        RxView.clicks(binding.modifyDone)
                .compose(this.bindToLifecycle())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {

                    private MaterialDialog mDialog;

                    @Override
                    public void accept(Object o) throws Exception {
                        bottomSheet.dismiss();
                        Logger.d("modify date start : " + selectedPlanReceivedDate + " " + startTime);
                        Logger.d("modify date end   : " + selectedPlanReceivedDate + " " + endTime);

                        if (mDialog == null) {
                            mDialog = new MaterialDialog.Builder(WayBillDetailActivity.this)
                                    .content("派送时间只能修改一次，如需再修改，请联系客服。")
                                    .positiveText("确定")
                                    .negativeText("取消")
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            presenter.modifyPlanReceivedDate(userInfo.getPhone(), logisticsWayBillDetailResultBean.getResult().get(0).getWaybill(), selectedPlanReceivedDate + " " + startTime, selectedPlanReceivedDate + " " + endTime);
                                        }
                                    })
                                    .build();
                        }
                        mDialog.show();
                    }
                });
    }

    @Override
    public void modifyPlanArriveTimeSuccess() {
        /**
         * 刷新状态
         */
        presenter.refreshLogisticsWayBillDetail(userInfo, waybill);
    }

    @Override
    public void modifyPlanArriveTimeFailed(String msg) {
        ToastManager.showCenterForShort(msg);
    }

    @Override
    public void onLoading() {
        dialog = KyeProgressDialog.show(this, dialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(dialog);
    }

    @Override
    public void onError() {

    }

    @Override
    public void onError(String msg) {
        ToastManager.showCenterForShort(msg);
    }

    @Override
    public void disableModifyArriveTimeButton() {
        binding.modifyPresentTime.setEnabled(false);
    }

    @Override
    public void enableModifyArriveTimeButton() {
        binding.modifyPresentTime.setEnabled(true);
    }

    @Override
    public LogisticsWayBillDetailResultBean getLogisticsWayBillDetailResultBean() {
        return logisticsWayBillDetailResultBean;
    }
}
